package com.yjz.study.account

import android.app.Application
import android.content.Context
import android.content.Intent
import android.text.TextUtils
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.yjz.common.restful.CallBack
import com.yjz.common.restful.HttpBaseResponse
import com.yjz.common.util.AppGlobals
import com.yjz.common.util.SPUtil
import com.yjz.study.cons.SPKeys
import com.yjz.study.http.ApiFactory
import com.yjz.study.http.api.AccountApi
import com.yjz.study.http.entity.res.UserProfile
import com.yjz.study.ui.biz.LoginActivity

/**
 *作用 :
 *作者 : yjz
 *时间 : 2025/3/24 16:30
 */
object AccountManager {

    private var boardingPass: String = ""

    // 登录成功转发
    private var loginLiveData = MutableLiveData<Boolean>()

    // 记录登录的observeForever的Observer，用来反注册，防止内存泄漏
    private var loginForeverObservers = mutableListOf<Observer<Boolean>>()

    // 获取用户信息转发
    private var userProfileLiveData = MutableLiveData<UserProfile>()
    private var userProfileForeverObservers = mutableListOf<Observer<UserProfile?>>()

    // 获取用户信息
    private var userProfile: UserProfile? = null

    // 是否正在请求信息
    private var fecting = false

    /**
     * 拉起登录页，并且同步注册观察者
     */
    fun login(context: Context? = AppGlobals.get(), observer: Observer<Boolean>) {
        if (context is LifecycleOwner) {
            loginLiveData.observe(context, observer)
        } else {
            loginLiveData.observeForever(observer)
            loginForeverObservers.add(observer)
        }
        val intent = Intent(context, LoginActivity::class.java)
        if (context is Application) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        }

        if (context == null) {
            throw IllegalArgumentException("context must not null!")
        }
        context.startActivity(intent)
    }

    /**
     * 判断是否登录
     */
    fun isLogin(): Boolean {
        return !TextUtils.isEmpty(boardingPass)
    }

    /**
     * 获取登录成功的boardingPass
     */
    fun getBoardingPass(): String {
        if (TextUtils.isEmpty(boardingPass)) {
            boardingPass = SPUtil.getString(SPKeys.BOARDING_PASS)
        }
        return boardingPass
    }

    /**
     * 登录成功转发
     */
    fun loginSuccess(boardingPass: String) {
        this.boardingPass = boardingPass
        SPUtil.putString(SPKeys.BOARDING_PASS, boardingPass)
        loginLiveData.value = true
        clearLoginForeverObservers()
    }

    /**
     * 清除登录的Observer
     */
    private fun clearLoginForeverObservers() {
        for (observer in loginForeverObservers) {
            loginLiveData.removeObserver(observer)
        }
        loginForeverObservers.clear()
    }

    /**
     * 获取用户信息
     * @param observer 注册观察者用来监听用户信息
     * @param onlyCache 是否获取缓存
     */
    @Synchronized
    fun getUserProfile(lifecycleOwner: LifecycleOwner?, observer: Observer<UserProfile?>, onlyCache: Boolean = true) {
        if (lifecycleOwner == null) {
            // observeForever 不会关联生命周期，需要自己维护生命周期，所以增加userProfileForeverObservers记录
            userProfileLiveData.observeForever(observer)
            userProfileForeverObservers.add(observer)
        } else {
            userProfileLiveData.observe(lifecycleOwner, observer)
        }
        // 判断是否是读取本地缓存
        if (userProfile != null && onlyCache) {
            userProfileLiveData.value = userProfile
            return
        }

        if (fecting) return
        fecting = true

        ApiFactory.create(AccountApi::class.java).profile()
            .enqueue(object : CallBack<UserProfile> {
                override fun onSuccess(response: HttpBaseResponse<UserProfile>) {
                    val responseData = response.data
                    if (response.successful() && responseData != null) {
                        userProfile = responseData
                        userProfileLiveData.value = userProfile
                    } else {
                        userProfileLiveData.value = null
                    }
                    clearProfileForeverObservers()
                    fecting = false
                }

                override fun onFailed(throwable: Throwable) {
                    userProfile = null
                    userProfileLiveData.value = null

                    fecting = false
                }
            })
    }

    private fun clearProfileForeverObservers() {
        for (observer in userProfileForeverObservers) {
            userProfileLiveData.removeObserver(observer)
        }
        userProfileForeverObservers.clear()
    }
}